/**
 * SMSDetailActivity.java
 * 
 * Create Version: 1.0
 * Author: lixh
 * Create Date: 2014-9-2
 * 
 */
package com.yinhai.activity;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.AsyncQueryHandler;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.telephony.SmsManager;
import android.text.InputType;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.lz.util.Utils;
import com.ray.ray.util.APNManager;
import com.ray.ray.util.MMSInfo;
import com.ray.ray.util.MMSSender;
import com.ray.ray.util.MMSUtil;
import com.yinhai.adapter.MessageBoxListAdapter;
import com.yinhai.constant.Contact;
import com.yinhai.model.ContactsUser;
import com.yinhai.model.MessageBean;
import com.yinhai.photo.utils.Photo;
import com.yinhai.util.Util;

/**
 * SMSDetailActivity （短信详情）
 * 
 * @author lixh
 */
public class SMSDetailActivity extends Activity implements OnScrollListener {
    String SENT_SMS_ACTION = "SENT_SMS_ACTION";
    
    private ListView talkView;
    
    private MessageBoxListAdapter adapter;
    
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    
    private AsyncQueryHandler asyncQuery;
    
    private AsyncQueryHandler caiXinQuery;
    
    private List<MessageBean> messages = new ArrayList<MessageBean>();;
    
    private EditText smsContent, smsTel, dialogEdit;
    
    private List<String> telList = new ArrayList<String>();
    
    private View topProgressView, bottomProgressView, footProgressView;
    
    private int visibleLastIndex = 0; // 最后的可视项索引
    
    private int visibleItemCount; // 当前窗口可见项总数
    
    private int currentTopPageNo = 1, currentBottomPageNo = 0, totalPage = 0;
    
    private boolean pageNOFlag = true;// 翻页标识 true：下翻页；false：上翻页；
    
    private AQuery aq;
    
    private int IsMMS = 0; // 0 , 短信 1，彩信
    
    private String FileImgPath = "";
    
    private AlertDialog popDialog = null;
    
    private final Uri CONTENT_URI = Uri.parse("content://mms/inbox"); // 查询彩信收件箱
    
    private final Uri CONTENT_URI_PART = Uri.parse("content://mms/part"); // 彩信附件表
    
    private String sendAddress;
    
    private Context ctx;
    
    /*
     * (non-Javadoc)
     * 
     * @see android.app.Activity#onCreate(android.os.Bundle)
     */
    private final static String ALBUM_PATH = Environment.getExternalStorageDirectory() + "/FS_TP/";
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.message_list_view);
        ctx = this;
        aq = new AQuery(this);
        smsContent = (EditText)this.findViewById(R.id.sms_content);
        if (getIntent().hasExtra("smsContent")) {
            smsContent.setText(getIntent().getStringExtra("smsContent"));
        }
        
        talkView = (ListView)this.findViewById(R.id.message_list);
        
        // 分页设置
        View loadMoreView = getLayoutInflater().inflate(R.layout.load_more, null);
        topProgressView = loadMoreView.findViewById(R.id.pg);
        talkView.addHeaderView(loadMoreView);
        
        loadMoreView = getLayoutInflater().inflate(R.layout.load_more, null);
        bottomProgressView = loadMoreView.findViewById(R.id.pg);
        talkView.addFooterView(loadMoreView);
        talkView.setOnScrollListener(this);
        
        loadMoreView = getLayoutInflater().inflate(R.layout.cx_view, null);
        footProgressView = loadMoreView.findViewById(R.id.layout_cx);
        talkView.addFooterView(loadMoreView);
        
        adapter = new MessageBoxListAdapter(SMSDetailActivity.this, messages);
        talkView.setAdapter(adapter);
        talkView.setDivider(null);
        if (getIntent().hasExtra("address")) {
            sendAddress = getIntent().getStringExtra("address");
        }
        
        // 查看短信
        if (getIntent().hasExtra("threadId")) {
            TextView textView = (TextView)this.findViewById(R.id.head_title);
            textView.setText(this.getIntent().getStringExtra("name"));
            if (this.getIntent().hasExtra("displayName") && this.getIntent().getStringExtra("displayName") != null
                && !"".equals(this.getIntent().getStringExtra("displayName"))) {
                textView.setText(this.getIntent().getStringExtra("displayName"));
            } else {
                textView.setText(this.getIntent().getStringExtra("address"));
            }
            telList.add(this.getIntent().getStringExtra("address"));
            totalSMS();
            query();
            // 新短信
        } else {
            TextView textView = (TextView)this.findViewById(R.id.head_title);
            textView.setText("新短信");
            findViewById(R.id.add_user_li).setVisibility(View.VISIBLE);
            smsTel = (EditText)this.findViewById(R.id.sms_tel);
        }
        aq.id(R.id.img_button).clicked(cre);
        
        aq.id(R.id.del_btn).clicked(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                footProgressView.setVisibility(View.GONE);
            }
        });
        
        aq.id(R.id.th_btn).clicked(cre);
        
        aq.id(R.id.ck_btn).clicked(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setDataAndType(Uri.parse("file://" + FileImgPath), "image/*");
                startActivity(intent);
            }
        });
        
        // 短信发送
        this.findViewById(R.id.sms_send).setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(View v) {
                
                // 不是发送的彩信
                if (IsMMS != 1) {
                    if (smsContent.getText().toString().trim().equals("")) {
                        Toast.makeText(SMSDetailActivity.this, "请填写内容", Toast.LENGTH_SHORT).show();
                        return;
                    }
                }
                if (telList == null || telList.isEmpty()) {
                    Toast.makeText(SMSDetailActivity.this, "请选择联系人", Toast.LENGTH_SHORT).show();
                    return;
                }
                
                if (IsMMS == 0) { // 发短信
                    // messages.clear();
                    
                    Intent sentIntent = new Intent(SENT_SMS_ACTION);
                    PendingIntent sentPI = PendingIntent.getBroadcast(SMSDetailActivity.this, 0, sentIntent, 0);
                    SmsManager smsManager = SmsManager.getDefault();
                    ArrayList<String> divideContents = smsManager.divideMessage(smsContent.getText().toString().trim());
                    
                    if (divideContents.size() == 1) {
                        for (String text : divideContents) {
                            for (String str : telList) {
                                smsManager.sendTextMessage(str, null, text, sentPI, null);
                            }
                        }
                    } else {
                        for (String str : telList) {
                            ArrayList<PendingIntent> sentIntents = new ArrayList<PendingIntent>();
                            sentIntents.add(PendingIntent.getBroadcast(SMSDetailActivity.this, 0, sentIntent, 0));
                            smsManager.sendMultipartTextMessage(str, null, divideContents, sentIntents, null);
                        }
                    }
                    
                    for (String str : telList) {
                        ContentValues values = new ContentValues();
                        // 发送时间
                        values.put("date", System.currentTimeMillis());
                        // 阅读状态
                        values.put("read", 0);
                        // 1为收 2为发
                        values.put("type", 2);
                        // 送达号码
                        values.put("address", str);
                        // 送达内容
                        values.put("body", smsContent.getText().toString().trim());
                        // 插入短信库
                        getContentResolver().insert(Uri.parse("content://sms/sent"), values);
                    }
                    if (getIntent().hasExtra("threadId") || (telList != null && telList.size() == 1)) {
                        findViewById(R.id.add_user_li).setVisibility(View.GONE);
                        if (!getIntent().hasExtra("threadId")) {
                            TextView textView = (TextView)findViewById(R.id.head_title);
                            textView.setText(smsTel.getText().toString());
                        }
                        // query();
                        messages.add(new MessageBean("", sdf.format(new Date()),
                            smsContent.getText().toString().trim(), R.layout.list_say_me_item));
                        talkView.setSelection(messages.size());
                        adapter.notifyDataSetChanged();
                    } else {
                        messages.add(new MessageBean("", sdf.format(new Date()),
                            smsContent.getText().toString().trim(), R.layout.list_say_me_item));
                        talkView.setSelection(messages.size());
                    }
                } else if (IsMMS == 1) { // 发彩信
                    MessageBean m =
                        new MessageBean("", sdf.format(new Date()), smsContent.getText().toString().trim(),
                            R.layout.list_say_me_item);
                    m.setType("2");
                    m.setFilePath(FileImgPath);
                    messages.add(m);
                    
                    talkView.setSelection(messages.size());
                    // SendMMS(smsContent.getText().toString().trim(), FileImgPath);
                    sendMMS(SMSDetailActivity.this, "", smsContent.getText().toString().trim(), FileImgPath, "");
                    footProgressView.setVisibility(View.GONE);
                }
                IsMMS = 0;
                aq.id(R.id.iv_img).image("");
                smsContent.setText("");
                ctx.sendBroadcast(new Intent("com.im.message"));
            }
        });
        
        // register the Broadcast Receivers
        this.registerReceiver(smsReceiver, new IntentFilter(SENT_SMS_ACTION));
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.im.message.smsdetail");
        this.registerReceiver(receiver, intentFilter);
        
    }
    
    /**
     * 弹出选择相册和拍照 框
     */
    OnClickListener cre = new OnClickListener() {
        
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            popDialog = Utils.showSetImageDialog(SMSDetailActivity.this, "", "", btnPickClick, btnTakePhotoClick, null);
        }
    };
    
    OnClickListener btnTakePhotoClick = new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (popDialog != null) {
                popDialog.dismiss();
            }
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            
            startActivityForResult(intent, 1);
        }
    };
    
    /**
     * 选择照片
     * */
    OnClickListener btnPickClick = new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (popDialog != null) {
                popDialog.dismiss();
            }
            Intent intent = new Intent(Intent.ACTION_PICK, null);
            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
            startActivityForResult(intent, 2);
        }
    };
    
    private BroadcastReceiver smsReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context _context, Intent _intent) {
            switch (getResultCode()) {
                case Activity.RESULT_OK:
                    Toast.makeText(SMSDetailActivity.this, "短信发送成功", Toast.LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                    break;
                case SmsManager.RESULT_ERROR_RADIO_OFF:
                    break;
                case SmsManager.RESULT_ERROR_NULL_PDU:
                    break;
            }
        }
    };
    
    // 查询短信条数
    private void totalSMS() {
        int count = 0;
        Cursor cursor = null;
        try {
            cursor =
                getContentResolver().query(Uri.parse("content://sms"),
                    new String[] {"count(*)"},
                    null,
                    null,
                    "date desc");
            if (this.getIntent().hasExtra("threadId") && this.getIntent().getStringExtra("threadId") != null
                && !"".equals(this.getIntent().getStringExtra("threadId"))) {
                cursor =
                    getContentResolver().query(Uri.parse("content://sms/conversations"),
                        new String[] {"thread_id", "msg_count", "snippet"},
                        "thread_id = " + this.getIntent().getStringExtra("threadId"),
                        null,
                        null);
                
            } else if (telList != null && telList.size() == 1) {
                cursor =
                    getContentResolver().query(Uri.parse("content://sms/conversations"),
                        new String[] {"thread_id", "msg_count", "snippet"},
                        "address=?",
                        new String[] {telList.get(0).startsWith("+86") ? telList.get(0) : "+86" + telList.get(0)},
                        null);
                
            }
            
            if (cursor == null || cursor.getCount() == 0)
                count = 0;
            for (int i = 0; i < cursor.getCount(); i++) {
                cursor.moveToPosition(i);
                count = cursor.getInt(1);
            }
            
        } catch (Exception e) {
            count = 0;
        } finally {
            cursor.close();
        }
        totalPage = count / Contact.LIMIT;
        if (count % Contact.LIMIT != 0) {
            totalPage += 1;
        }
    }
    
    private void query() {
        int pageNo = pageNOFlag ? currentBottomPageNo-- : currentTopPageNo++;
        asyncQuery = new MessageAsynQueryHandler(this.getContentResolver(), this);
        Uri uri = Uri.parse("content://sms");
        String[] projection = new String[] {"date", "address", "person", "body", "type", "_id"}; // 查询的列
        if (this.getIntent().hasExtra("threadId") && this.getIntent().getStringExtra("threadId") != null
            && !"".equals(this.getIntent().getStringExtra("threadId"))) {
            asyncQuery.startQuery(0, null, uri, projection, "thread_id = "
                + this.getIntent().getStringExtra("threadId"), null, "date desc  limit " + pageNo * Contact.LIMIT + ","
                + Contact.LIMIT);
            // asyncQuery.startQuery(0, null, uri, projection, "thread_id = "
            // + this.getIntent().getStringExtra("threadId"), null,"  limit 0,10");
        } else if (telList != null && telList.size() == 1) { // 短信
            asyncQuery.startQuery(0,
                null,
                uri,
                projection,
                "address=?",
                new String[] {telList.get(0).startsWith("+86") ? telList.get(0) : "+86" + telList.get(0)},
                "date desc limit " + pageNo * Contact.LIMIT + "," + Contact.LIMIT);
            // asyncQuery.startQuery(
            // 0,
            // null,
            // uri,
            // projection,
            // "address=?",
            // new String[] { telList.get(0).startsWith("+86") ? telList
            // .get(0) : "+86" + telList.get(0) },null);
        }
    }
    
    /**
     * 查询彩信
     */
    private List<MessageBean> queryCaixin() {
        ContentResolver contentResolver = ctx.getContentResolver();
        Uri uri = Uri.parse("content://mms");
        String[] projection = new String[] {"_id", "date", "msg_box"}; // 查询的列
        Cursor cursor = null;
        if (this.getIntent().hasExtra("threadId") && this.getIntent().getStringExtra("threadId") != null
            && !"".equals(this.getIntent().getStringExtra("threadId"))) {
            cursor =
                contentResolver.query(uri,
                    projection,
                    "thread_id = " + this.getIntent().getStringExtra("threadId"),
                    null,
                    "date asc");
        }
        
        List<MessageBean> messages = new ArrayList<MessageBean>();
        if (cursor != null && cursor.getCount() > 0) {
            cursor.moveToFirst();
            for (int i = 0; i < cursor.getCount(); i++) {
                cursor.moveToPosition(i);
                String mid = cursor.getString(cursor.getColumnIndex("_id"));
                String date = sdf.format(new Date(cursor.getLong(cursor.getColumnIndex("date")) * 1000));
                String msg_box = cursor.getString(cursor.getColumnIndex("msg_box"));
                MessageBean d = new MessageBean();
                d.setType("2");
                d.setDate(date);
                d.setId(mid);
                ContentResolver contentResolverPart = ctx.getContentResolver();
                String[] projectionPart = new String[] {"mid","_id", "seq", "ct", "_data", "text"}; // 查询的列
                Cursor cursorPart = null;
                try {
                    cursorPart =
                        contentResolverPart.query(Uri.parse("content://mms/part"), projectionPart, new String("mid="
                            + mid), null, null);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                
                if (cursorPart != null && cursorPart.getCount() > 0) {
                    cursorPart.moveToFirst();
                    for (int j = 0; j < cursorPart.getCount(); j++) {
                        cursorPart.moveToPosition(j);
                        if (!"-1".equals(cursorPart.getString(cursorPart.getColumnIndex("seq")))) {
                            String ct = cursorPart.getString(cursorPart.getColumnIndex("ct"));
                            
                            if ("text/plain".equals(ct)) {
                                String data = cursorPart.getString(cursorPart.getColumnIndex("_data"));
                                if (data != null) {
                                    d.setText(d.getText()+ getMmsText(mid));
                                } else {
                                    d.setText(d.getText()+cursorPart.getString(cursorPart.getColumnIndex("text")));
                                }
                            } else if ("image/png".equals(cursorPart.getString(cursorPart.getColumnIndex("ct")))
                                || "image/jpeg".equals(cursorPart.getString(cursorPart.getColumnIndex("ct")))
                                || "image/gif".equals(cursorPart.getString(cursorPart.getColumnIndex("ct")))) {
                                // 图片
                                //d.setBitmap(Photo.zoomImg(getMmsImage(cursorPart.getString(cursorPart.getColumnIndex("_id"))), com.yinhai.util.Utils.dip2px(this, 100), ctx));
                                d.setFilePath(cursorPart.getString(cursorPart.getColumnIndex("_id")));
                            } else {
                                d.setText(d.getText()+cursorPart.getString(cursorPart.getColumnIndex("text")));
                            }
                        }
                    }
                }
                if ("2".equals(msg_box)) {
                    // 发送者
                    d.setLayoutID(R.layout.list_say_me_item);
                } else {
                    // 接受者
                    d.setLayoutID(R.layout.list_say_he_item);
                }
                d.setName(sendAddress);
                messages.add(d);
            }
            
        }
        if (cursor != null) {
            cursor.close();
        }
        
        return messages;
    }
    
    private String getMmsText(String id) {
        Uri partURI = Uri.parse("content://mms/part/" + id);
        InputStream is = null;
        StringBuilder sb = new StringBuilder();
        try {
            is = getContentResolver().openInputStream(partURI);
            if (is != null) {
                InputStreamReader isr = new InputStreamReader(is, "UTF-8");
                BufferedReader reader = new BufferedReader(isr);
                String temp = reader.readLine();
                while (temp != null) {
                    sb.append(temp);
                    temp = reader.readLine();
                }
            }
        } catch (IOException e) {
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                }
            }
        }
        return sb.toString();
    }
    private Bitmap getMmsImage(String _id) {  
        Uri partURI = Uri.parse("content://mms/part/" + _id);  
        InputStream is = null;  
        Bitmap bitmap = null;  
        try {  
            is = getContentResolver().openInputStream(partURI);  
            bitmap = BitmapFactory.decodeStream(is);  
        } catch (Exception e) {e.printStackTrace();}  
        finally {  
            if (is != null) {  
                try {  
                    is.close();  
                } catch (IOException e) {}  
            }  
        }  
        return bitmap;  
    }  
    // 查询短信
    private class MessageAsynQueryHandler extends AsyncQueryHandler {
        private Context contextt;
        
        public MessageAsynQueryHandler(ContentResolver cr, Context context) {
            super(cr);
            contextt = context;
        }
        
        @Override
        protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
            
            List<MessageBean> tempList = new ArrayList<MessageBean>();
            if (cursor != null && cursor.getCount() > 0) {
                cursor.moveToFirst();
                for (int i = cursor.getCount() - 1; i >= 0; i--) {
                    cursor.moveToPosition(i);
                    String date = sdf.format(new Date(cursor.getLong(cursor.getColumnIndex("date"))));
                    if (cursor.getInt(cursor.getColumnIndex("type")) == 1) {
                        MessageBean d =
                            new MessageBean(cursor.getString(cursor.getColumnIndex("address")), date,
                                cursor.getString(cursor.getColumnIndex("body")), R.layout.list_say_he_item,
                                cursor.getString(cursor.getColumnIndex("_id")));
                        tempList.add(d);
                    } else {
                        MessageBean d =
                            new MessageBean(cursor.getString(cursor.getColumnIndex("address")), date,
                                cursor.getString(cursor.getColumnIndex("body")), R.layout.list_say_me_item,
                                cursor.getString(cursor.getColumnIndex("_id")));
                        tempList.add(d);
                    }
                }
            }
            tempList.addAll(queryCaixin());
            if (tempList.size() > 0) {
                if (pageNOFlag) {
                    messages.addAll(tempList);
                } else {
                    messages.addAll(0, tempList);
                }
                if (messages.size() >= 4 * Contact.LIMIT) {
                    if (pageNOFlag) {
                        int number = messages.size() - 3 * Contact.LIMIT;
                        for (int i = 0; i < number; i++) {
                            messages.remove(i);
                        }
                        currentTopPageNo--;
                        adapter.notifyDataSetChanged();
                        talkView.setSelection(messages.size() - Contact.LIMIT);
                    } else {
                        int number = messages.size() - Contact.LIMIT;
                        for (int i = messages.size() - 1; i > number; i--) {
                            messages.remove(i);
                        }
                        currentBottomPageNo++;
                        adapter.notifyDataSetChanged();
                        talkView.setSelection(Contact.LIMIT);
                    }
                } else {
                    adapter.notifyDataSetChanged();
                    if (messages.size() <= Contact.LIMIT) {
                        talkView.setSelection(messages.size() - 1);
                    }
                }
                
            }
            
            super.onQueryComplete(token, cookie, cursor);
        }
    }
    
    private class CaiXinAsynQueryHandler extends AsyncQueryHandler {
        private Context contextt;
        
        public CaiXinAsynQueryHandler(ContentResolver cr, Context context) {
            super(cr);
            contextt = context;
        }
        
        @Override
        protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
            
            List<MessageBean> tempList = new ArrayList<MessageBean>();
            if (cursor != null && cursor.getCount() > 0) {
                cursor.moveToFirst();
                for (int i = cursor.getCount() - 1; i >= 0; i--) {
                    cursor.moveToPosition(i);
                    String date = sdf.format(new Date(cursor.getLong(cursor.getColumnIndex("date"))));
                    if (cursor.getInt(cursor.getColumnIndex("type")) == 1) {
                        MessageBean d =
                            new MessageBean(cursor.getString(cursor.getColumnIndex("address")), date,
                                cursor.getString(cursor.getColumnIndex("body")), R.layout.list_say_he_item,
                                cursor.getString(cursor.getColumnIndex("_id")));
                        tempList.add(d);
                    } else {
                        MessageBean d =
                            new MessageBean(cursor.getString(cursor.getColumnIndex("address")), date,
                                cursor.getString(cursor.getColumnIndex("body")), R.layout.list_say_me_item,
                                cursor.getString(cursor.getColumnIndex("_id")));
                        tempList.add(d);
                    }
                }
                if (tempList.size() > 0) {
                    if (pageNOFlag) {
                        messages.addAll(tempList);
                    } else {
                        messages.addAll(0, tempList);
                    }
                    if (messages.size() >= 4 * Contact.LIMIT) {
                        if (pageNOFlag) {
                            int number = messages.size() - 3 * Contact.LIMIT;
                            for (int i = 0; i < number; i++) {
                                messages.remove(i);
                            }
                            currentTopPageNo--;
                            adapter.notifyDataSetChanged();
                            talkView.setSelection(messages.size() - Contact.LIMIT);
                        } else {
                            int number = messages.size() - Contact.LIMIT;
                            for (int i = messages.size() - 1; i > number; i--) {
                                messages.remove(i);
                            }
                            currentBottomPageNo++;
                            adapter.notifyDataSetChanged();
                            talkView.setSelection(Contact.LIMIT);
                        }
                    } else {
                        adapter.notifyDataSetChanged();
                        if (messages.size() <= Contact.LIMIT) {
                            talkView.setSelection(messages.size() - 1);
                        }
                    }
                    
                } else {
                    Toast.makeText(contextt, "没有短信进行操作", Toast.LENGTH_SHORT).show();
                }
            }
            super.onQueryComplete(token, cookie, cursor);
        }
    }
    
    @Override
    protected void onDestroy() {
        unregisterReceiver(smsReceiver);
        unregisterReceiver(receiver);
        super.onDestroy();
    }
    
    // 返回
    public void doBack(View view) {
        onBackPressed();
    }
    
    // 添加发送人员
    public void doAddUser(View view) {
        String[] buttonArr = new String[] {"清空选择", "本地通讯录", "集团通讯录", "手动添加"};
        new AlertDialog.Builder(this).setTitle("操作选择").setItems(buttonArr, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                
                // 清空选择
                    case 0:
                        smsTel.setText("");
                        telList.clear();
                        break;
                    
                    // 本地通讯录
                    case 1: {
                        Intent intent = new Intent(SMSDetailActivity.this, ContactActivity.class);
                        intent.putExtra("isMutiCheck", true);
                        intent.putExtra("userType", 1);
                        startActivityForResult(intent, 123456);
                    }
                        break;
                    // 集团通讯录
                    case 2: {
                        Intent intent = new Intent(SMSDetailActivity.this, ContactActivity.class);
                        intent.putExtra("isMutiCheck", true);
                        intent.putExtra("userType", 2);
                        startActivityForResult(intent, 123456);
                    }
                        break;
                    // 手动添加
                    case 3:
                        dialogEdit = new EditText(SMSDetailActivity.this);
                        dialogEdit.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
                            LayoutParams.WRAP_CONTENT));
                        dialogEdit.setHint("提示:多个号码以逗号分隔");
                        dialogEdit.setInputType(InputType.TYPE_CLASS_PHONE);
                        new AlertDialog.Builder(SMSDetailActivity.this).setTitle("请输入短信号码")
                            .setView(dialogEdit)
                            .setNeutralButton("取消", new DialogInterface.OnClickListener() {
                                
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    
                                }
                            })
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    if (smsTel.getText().toString().equals("")) {
                                        smsTel.setText(dialogEdit.getText().toString());
                                    } else {
                                        smsTel.setText(smsTel.getText().toString() + ","
                                            + dialogEdit.getText().toString());
                                    }
                                    for (String str : smsTel.getText().toString().split(",")) {
                                        telList.add(str);
                                    }
                                }
                            })
                            .show();
                        break;
                }
            }
        })
            .show();
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 123456 && resultCode == RESULT_OK) {
            String text = smsTel.getText().toString();
            for (ContactsUser user : (List<ContactsUser>)data.getSerializableExtra("data")) {
                if (text.equals("")) {
                    text = user.getName();
                } else {
                    text += "," + user.getName();
                }
                telList.add(user.getTelPhone());
            }
            smsTel.setText(text);
            
        } else if (requestCode == 2) { // 选择照片
            if (data != null) {
                InputStream input = null;
                try {
                    input = getContentResolver().openInputStream(data.getData());
                    Bitmap photo = BitmapFactory.decodeStream(input);
                    saveFile(photo, "123345.jpg");
                    aq.id(R.id.iv_img).image(photo);
                    
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                
            }
            
        } else if (requestCode == 1) { // 拍照
            Bundle bundle = data.getExtras();
            Bitmap bitmapTemp = (Bitmap)bundle.get("data");// 获取相机返回的数据，并转换为Bitmap图片格式
            try {
                saveFile(bitmapTemp, "123345.jpg");
                aq.id(R.id.iv_img).image(bitmapTemp);
                
            } catch (Exception e) {
                e.printStackTrace();
            }
            
        }
    }
    
    public void saveFile(Bitmap bm, String fileName) {
        File dirFile = new File(ALBUM_PATH);
        if (!dirFile.exists()) {
            dirFile.mkdir();
        }
        try {
            File myCaptureFile = new File(ALBUM_PATH + fileName);
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
            bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
            FileImgPath = myCaptureFile + "";
            IsMMS = 1;
            footProgressView.setVisibility(View.VISIBLE);
            bos.flush();
            bos.close();
        } catch (Exception e) {
            e.printStackTrace();
            IsMMS = 0;
        }
        
    }
    
    /**
     * 发MMS
     * 
     * @param context
     * @param number
     * @param subject
     * @param text
     * @param imagePath
     * @param audioPath
     */
    public void sendMMS(final Context context, String subject, String text, String imagePath, String audioPath) {
        for (int i = 0; i < telList.size(); i++) {
            
            final MMSInfo mmsInfo = new MMSInfo(context, telList.get(i), subject, text, imagePath, audioPath);
            final List<String> list = APNManager.getSimMNC(context);
            
            new Thread() {
                @Override
                public void run() {
                    try {
                        byte[] res = MMSSender.sendMMS(context, list, mmsInfo.getMMSBytes());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                };
            }.start();
            
        }
        MMSUtil.insert(context, new String[] {sendAddress}, subject, imagePath, text);
    }
    
    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        this.visibleItemCount = visibleItemCount;
        visibleLastIndex = firstVisibleItem + visibleItemCount - 1;
    }
    
    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        int itemsLastIndex = talkView.getAdapter().getCount() - 1; // 数据集最后一项的索引
        int lastIndex = itemsLastIndex + 1; // 加上底部的loadMoreView项
        if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
            if (visibleLastIndex > lastIndex - 3 && currentBottomPageNo >= 0) {
                bottomProgressView.setVisibility(View.VISIBLE);
                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        pageNOFlag = true;
                        loadMore();
                    }
                    
                });
            } else if (view.getFirstVisiblePosition() - 3 <= 0 && currentTopPageNo < totalPage) {
                topProgressView.setVisibility(View.VISIBLE);
                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        pageNOFlag = false;
                        loadMore();
                    }
                    
                });
            }
        }
        
    }
    
    // true：下翻页；false：上翻页
    private void loadMore() {
        query();
        topProgressView.setVisibility(View.GONE);
        bottomProgressView.setVisibility(View.GONE);
    }
    
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                if (intent.getAction().equals("com.im.message.smsdetail")) {
                    messages.clear();
                    totalSMS();
                    query();
                }
                
            } catch (Exception e) {
                e.printStackTrace();
            }
            
        }
    };
    
}
